package com.hohd.up.controller;


import com.hohd.up.pojo.AjaxJson;
import lombok.Cleanup;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/res")
public class ResController {
    public AjaxJson<String> up(String img) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();

        return ajaxJson;
    }

    @Value("${html.path}")
    String imagePath;

    @RequestMapping(params = "savePng")
    public AjaxJson<String> savePng(String png) throws IOException {
        // 1.自己
        // 2.部门经理
        // 3.信息中心审核员
        // 4.信息中心主任
        // 5.采购经理
        // 6.采购副总
        AjaxJson<String> ajaxJson = new AjaxJson<String>();
        if (null == png || "".equals(png)) {
            ajaxJson.data = "程序有问题，请联系管理员";
            ajaxJson.code = -1;
            return ajaxJson;
        }
        byte[] b64Png = Base64.decodeBase64(png.replace("data:image/png;base64,", ""));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String savedFileName = uuid + ".png";
        String pathname = imagePath + File.separator + savedFileName;

        @Cleanup
        FileOutputStream fos = new FileOutputStream(pathname);
        fos.write(b64Png);
        fos.flush();
        ajaxJson.data = savedFileName;
        return ajaxJson;
    }
}
